import Vue from 'vue'
import VueRouter from 'vue-router'
import { Message } from 'element-ui'

import Home from '@/views/Home'
import Register from '@/views/Register'
import Search from '@/views/Search'
import Login from '@/views/Login'
import Detail from '@/views/Detail'
import Cart from '@/views/Cart'
import AddCartSuccess from '@/views/AddCartSuccess'
import Trade from '@/views/Trade'
import Pay from '@/views/Pay'
import Center from '@/views/Center'
import PaySuccess from '@/views/PaySuccess'

Vue.use(VueRouter)
const routes = [
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: {
      title: '尚品汇-首页',
    },
  },
  {
    path: '/search',
    name: 'Search',
    component: Search,
    meta: {
      title: '尚品汇-搜索',
    },
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      isHideFooter: true,
      title: '尚品汇-登录',
    },
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: {
      isHideFooter: true,
      title: '尚品汇-注册',
    },
  },
  {
    path: '/detail/:id',
    name: 'Detail',
    component: Detail,
    meta: {
      isHideFooter: true,
      title: '尚品汇-详情',
    },
  },
  {
    path: '/addcart_success',
    name: 'AddCartSuccess',
    component: AddCartSuccess,
    meta: {
      isLogin: true,
      title: '尚品汇-加入购物车',
    },
  },
  {
    path: '/cart',
    name: 'Cart',
    component: Cart,
    meta: {
      isLogin: true,
      title: '尚品汇-购物车',
    },
  },
  {
    path: '/trade',
    name: 'Trade',
    component: Trade,
    meta: {
      isLogin: true,
      title: '尚品汇-订单详情',
    },
  },
  {
    path: '/pay',
    name: 'Pay',
    component: Pay,
    meta: {
      isLogin: true,
      title: '尚品汇-支付',
    },
  },
  {
    path: '/center',
    name: 'Center',
    component: Center,
    meta: {
      isLogin: true,
      title: '尚品汇-我的订单',
    },
  },
  {
    path: '/paysuccess',
    name: 'PaySuccess',
    component: PaySuccess,
    meta: {
      isLogin: true,
      title: '尚品汇-我的订单',
    },
  },
  {
    path: '/',
    redirect: '/home',
  },
]
const router = new VueRouter({
  mode: 'history',
  routes,
  scrollBehavior() {
    // 始终滚动到顶部
    return { x: 0, y: 0 }
  },
})

// 全局前置导航守卫  router.beforeEach
const path = routes.reduce((pre, cur) => {
  if (cur.meta?.isLogin) {
    pre.push(cur.path)
  }
  return pre
}, [])
router.beforeEach((to, from, next) => {
  const token = JSON.parse(localStorage.getItem('userInfo'))?.token

  if (token) {
    if (to.path == '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    if (path.includes(to.path)) {
      Message.warning('请先登录')
      next(`/login?redirect=${to.path}`)
    } else {
      next()
    }
  }
})

// 全局后置导航守卫  router.afterEach
router.afterEach((to) => {
  document.title = to.meta.title
})
export default router
